package com.app.studyroom;

import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.adapter.BookingRecordAdapter;
import com.app.studyroom.adapter.SeatManageAdapter;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrSeat.DeleteSeatBookingRequest;
import com.app.studyroom.api.model.ssrSeat.PageSeatListRequest;
import com.app.studyroom.api.model.ssrSeat.PageSeatListResponse;
import com.app.studyroom.api.model.ssrSeat.SeatDeatilBean;
import com.app.studyroom.api.model.ssrSeat.SeatDeatilRequest;
import com.app.studyroom.api.model.ssrSeat.SeatDeleteRequest;
import com.app.studyroom.api.model.ssrSeat.SeatItem;
import com.app.studyroom.api.model.ssrSeat.SeatSaveRequest;
import com.app.studyroom.api.model.ssrSeat.SeatUpdateRequest;
import com.app.studyroom.api.model.ssrUser.BindUserRequest;
import com.app.studyroom.api.model.ssrUser.QyAdminListRequest;
import com.app.studyroom.api.model.ssrUser.UserIdRequest;
import com.app.studyroom.api.model.ssrUser.UserItem;
import com.app.studyroom.custom.spinner.SearchableSpinner;
import com.app.studyroom.db.UserInfo;
import com.app.studyroom.mapper.AreaNameToIdMapper;
import com.app.studyroom.mapper.SeatStatusMapper;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AdminSeatControlActivity extends BaseActivity {

    private RecyclerView recyclerView;
    private SeatManageAdapter seatAdapter;
    private List<SeatItem> seatList = new ArrayList<>();
    private ApiService apiService;

    private EditText editSeatNum;
    private Spinner spinnerArea, spinnerAdmin, spinnerFilterArea;
    private SearchableSpinner spinnerBindUser;
    private String selectedFilterAreaId = "";
    private Button btnAddSeat;
    private ImageView ic_back;

    private SeatItem editingSeat = null;

    private String token;

    private int currentPage = 1;
    private final int pageSize = 11;

    //存储映射
    private final Map<String, String> qyAdminMap = new HashMap<>();
    private final Map<String, String> bindUserMap = new HashMap<>();
    // 全局添加一个反向映射
    private final Map<String, String> userIdToDisplayMap = new HashMap<>();
    private final Map<String, String> seatBindIdToNameCache = new HashMap<>();

    //按时刷新
    private final long REFRESH_INTERVAL_MS = 60 * 1000; // 一分钟
    private final android.os.Handler refreshHandler = new android.os.Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seat_control);

        token = getSharedPreferences("Session", MODE_PRIVATE).getString("token", "").trim();
        apiService = ApiClient.getClient().create(ApiService.class);

        recyclerView = findViewById(R.id.seat_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        seatAdapter = new SeatManageAdapter(seatList, new SeatManageAdapter.OnSeatActionListener() {
            @Override
            public void onEdit(SeatItem seat) {
                Log.i("请求", "" + new Gson().toJson(new SeatDeatilRequest(seat.getId())));
                apiService.seatDeatil(token, new SeatDeatilRequest(seat.getId())).enqueue(new Callback<ApiResponse<SeatDeatilBean>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<SeatDeatilBean>> call, Response<ApiResponse<SeatDeatilBean>> response) {

                        if (response.body() != null && response.body().getCode() == 200) {
                            SeatDeatilBean bean = response.body().getData();
//                            bean.setQyAdminMap(seat.getQyAdminMap());
                            editItme(bean);
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<SeatDeatilBean>> call, Throwable t) {
                        Toast.makeText(AdminSeatControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onDelete(SeatItem seat) {
                SeatDeleteRequest deleteRequest = new SeatDeleteRequest(seat.getId());
                apiService.seatDelete(token, deleteRequest).enqueue(new Callback<ApiResponse<Object>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            ApiResponse<Object> resp = response.body();
                            if (resp.getCode() == 200) {
                                Toast.makeText(AdminSeatControlActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                                loadSeatList();
                            } else {
                                Toast.makeText(AdminSeatControlActivity.this, "删除失败：" + resp.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(AdminSeatControlActivity.this, "请求失败：" + response.code(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                        Toast.makeText(AdminSeatControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }, seatBindIdToNameCache);

        recyclerView.setAdapter(seatAdapter);
        spinnerArea = findViewById(R.id.spinnerArea);
        spinnerAdmin = findViewById(R.id.spinnerAdmin);
        spinnerFilterArea = findViewById(R.id.spinnerFilterArea);

        // 获取身份和管理员信息
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String identity = sp.getString("identity", "");
        String currentAdminId = String.valueOf(sp.getLong("userId", 0L));
        String currentAdminName = sp.getString("userName", "");
        String userQy = sp.getString("qy", "");

        // 区域管理员或超级管理员配置管理员下拉框
        if ("区域管理员".equals(identity)) {
            List<String> adminNames = new ArrayList<>();
            adminNames.add(currentAdminName);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adminNames);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerAdmin.setAdapter(adapter);
            spinnerAdmin.setSelection(0);
            qyAdminMap.clear();
            qyAdminMap.put(currentAdminName, currentAdminId);
        } else if ("超级管理员".equals(identity)) {
            loadAllQyAdmins();
        }

        // ✅✅✅ 修改区域选择逻辑：无论是谁都能筛选区域
        List<String> allAreasList = new ArrayList<>();
        allAreasList.add("全部"); // 添加“全部”选项
        for (String area : AreaNameToIdMapper.getAllAreaNames()) {
            allAreasList.add(area);
        }
        String[] areaNames = allAreasList.toArray(new String[0]); // 替代旧 areaNames

        // 区域筛选 Spinner（spinnerFilterArea）适配器与监听器
        ArrayAdapter<String> filterAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, areaNames);
        filterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerFilterArea.setAdapter(filterAdapter);

        spinnerFilterArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String areaName = parent.getItemAtPosition(position).toString();
                if ("全部".equals(areaName)) {
                    selectedFilterAreaId = "";  // 不筛选
                } else {
                    selectedFilterAreaId = AreaNameToIdMapper.getIdByName(areaName);
                }
                currentPage = 1;
                loadSeatList();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedFilterAreaId = "";
            }
        });

        // 用于添加座位，所有身份都显示所有区域（不含“全部”）
        String[] areaNamesForAdd = AreaNameToIdMapper.getAllAreaNames();
        ArrayAdapter<String> areaAdapter = new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, areaNamesForAdd);
        areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerArea.setAdapter(areaAdapter);
        spinnerBindUser = findViewById(R.id.spinnerBindUser);
        editSeatNum = findViewById(R.id.editSeatNum);
        btnAddSeat = findViewById(R.id.btnAddSeat);
        ic_back = findViewById(R.id.ic_back);

        // 监听区域改变，加载对应可绑定用户
        spinnerArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedAreaName = parent.getItemAtPosition(position).toString();
                String seatPlace = AreaNameToIdMapper.getIdByName(selectedAreaName);
                loadBindableUsers(seatPlace);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                loadBindableUsers(null);
            }
        });

        ic_back.setOnClickListener(v -> onBackPressed());

        btnAddSeat.setOnClickListener(v -> {
            String seatPlace = AreaNameToIdMapper.getIdByName(spinnerArea.getSelectedItem().toString());
            String selectedAdminName = spinnerAdmin.getSelectedItem().toString();
            String qyAdmin = qyAdminMap.get(selectedAdminName);
            if (qyAdmin == null || qyAdmin.isEmpty()) {
                Toast.makeText(this, "管理员ID异常", Toast.LENGTH_SHORT).show();
                return;
            }
            String seatNum = editSeatNum.getText().toString().trim();
            String bindUserDisplay = spinnerBindUser.getSelectedItem() != null ?
                    spinnerBindUser.getSelectedItem().toString() : null;
            String bindUser = (bindUserDisplay != null && bindUserMap.containsKey(bindUserDisplay)) ?
                    bindUserMap.get(bindUserDisplay) : null;

            if (seatPlace.isEmpty() || qyAdmin.isEmpty() || seatNum.isEmpty()) {
                Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }

            if (editingSeat == null) {
                SeatSaveRequest saveRequest = new SeatSaveRequest(seatPlace, qyAdmin, seatNum);
                saveRequest.setSeatBind(bindUser);
                saveRequest.setSeatStatus("0");
                apiService.seatSave(token, saveRequest).enqueue(new Callback<ApiResponse<Object>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getCode() == 200) {
                            Toast.makeText(AdminSeatControlActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                            clearForm();
                            loadSeatList();
                        } else {
                            Toast.makeText(AdminSeatControlActivity.this, "添加失败：" + response.body().getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                        Toast.makeText(AdminSeatControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                SeatUpdateRequest updateRequest = new SeatUpdateRequest(editingSeat.getId(), seatPlace, qyAdmin);
                updateRequest.setSeatBind(bindUser);
                apiService.seatUpdate(token, updateRequest).enqueue(new Callback<ApiResponse<Object>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getCode() == 200) {
                            Toast.makeText(AdminSeatControlActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                            clearForm();
                            loadSeatList();
                        } else {
                            Toast.makeText(AdminSeatControlActivity.this, "修改失败：" + response.body().getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                        Toast.makeText(AdminSeatControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        loadSeatList();

        Button btnPrev = findViewById(R.id.btnPrevPage);
        Button btnNext = findViewById(R.id.btnNextPage);

        btnPrev.setOnClickListener(v -> {
            if (currentPage > 1) {
                currentPage--;
                loadSeatList();
            } else {
                Toast.makeText(this, "已经是第一页", Toast.LENGTH_SHORT).show();
            }
        });
        btnNext.setOnClickListener(v -> {
            currentPage++;
            loadSeatList();
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshHandler.post(refreshRunnable);
    }

    @Override
    protected void onPause() {
        super.onPause();
        refreshHandler.removeCallbacks(refreshRunnable);
    }


    private void clearForm() {
        spinnerArea.setSelection(0);
        spinnerAdmin.setSelection(0);
        spinnerBindUser.setSelection(0);
        editingSeat = null;
        editSeatNum.setText("");
        btnAddSeat.setText("添加座位");
    }

    private void loadSeatList() {
        PageSeatListRequest request = new PageSeatListRequest(currentPage, pageSize);
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);

        String identity = sp.getString("identity", "");
        if (("超级管理员".equals(identity) || "区域管理员".equals(identity)) && !selectedFilterAreaId.isEmpty()) {
            request.setSeatPlace(selectedFilterAreaId);
        }

        Log.d("SeatListRequest", "请求体 JSON: " + new Gson().toJson(request));

        apiService.pageSeatList(token.trim(), request).enqueue(new Callback<PageSeatListResponse>() {
            @Override
            public void onResponse(Call<PageSeatListResponse> call, Response<PageSeatListResponse> response) {
                if (response.body() == null || response.body().getData() == null || response.body().getData().getData() == null) {
                    Toast.makeText(AdminSeatControlActivity.this, "加载失败：响应体为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                List<SeatItem> seats = response.body().getData().getData();
                Log.i("测试5", "" + new Gson().toJson(response.body()));
                // UI 显示页码和按钮状态
                TextView tvPage = findViewById(R.id.tvPageIndicator);
                Button btnPrev = findViewById(R.id.btnPrevPage);
                Button btnNext = findViewById(R.id.btnNextPage);

                tvPage.setText("第 " + currentPage + " 页");
                int total = response.body().getData().getTotal();
                boolean isLastPage = currentPage * pageSize >= total;
                btnPrev.setEnabled(currentPage > 1);
                btnNext.setEnabled(!isLastPage);
                btnPrev.setAlpha(currentPage > 1 ? 1.0f : 0.4f);
                btnNext.setAlpha(!isLastPage ? 1.0f : 0.4f);

                // 👇 收集所有需要查询的 userId
                List<SeatItem> seatsNeedingName = new ArrayList<>();
                for (SeatItem seat : seats) {
                    String userId = seat.getSeatBind();
                    if (userId == null || userId.trim().isEmpty()) {
                        seat.setSeatBind("无");
                    } else if (seatBindIdToNameCache.containsKey(userId)) {
                        seat.setSeatBind(seatBindIdToNameCache.get(userId));
                    } else {
                        seat.setSeatBind(userId);  // 先用ID占位
                        seatsNeedingName.add(seat);
                    }
                }

                // 👇 如果没有需要请求的，直接刷新 UI
                if (seatsNeedingName.isEmpty()) {
                    seatList = seats;
                    Log.i("数据1", "" + new Gson().toJson(seatList));
                    seatAdapter.setSeatList(seatList);
                    return;
                }

                // 👇 否则，等全部异步请求返回后再刷新 adapter
                final int[] counter = {seatsNeedingName.size()};
                for (SeatItem seat : seatsNeedingName) {
                    String userId = seat.getSeatBind();
                    if (userId != null && !"无".equals(userId.trim()) && !"null".equalsIgnoreCase(userId.trim())) {
                        try {
                            long userIdLong = Long.parseLong(userId.trim());
                            UserIdRequest uidRequest = new UserIdRequest(userIdLong);
                            apiService.getUserById(uidRequest).enqueue(new Callback<ApiResponse<UserInfo>>() {
                                @Override
                                public void onResponse(Call<ApiResponse<UserInfo>> call, Response<ApiResponse<UserInfo>> res) {
                                    if (res.isSuccessful() && res.body() != null && res.body().getCode() == 200) {
                                        String name = res.body().getData().getUserName();
                                        seatBindIdToNameCache.put(userId, name);
                                    }
                                    counter[0]--;
                                    if (counter[0] == 0) {
                                        seatList = seats;

                                        seatAdapter.setSeatList(seatList); // 刷新 UI
                                    }
                                }

                                @Override
                                public void onFailure(Call<ApiResponse<UserInfo>> call, Throwable t) {
                                    counter[0]--;
                                    if (counter[0] == 0) {
                                        seatList = seats;
                                        Log.i("数据3", "" + new Gson().toJson(seatList));

                                        seatAdapter.setSeatList(seatList);
                                    }
                                }
                            });
                        } catch (NumberFormatException e) {
                            Log.w("SeatBind", "跳过非法 userId: " + userId);
                            counter[0]--;
                            if (counter[0] == 0) {
                                seatList = seats;
                                Log.i("数据4", "" + new Gson().toJson(seatList));

                                seatAdapter.setSeatList(seatList);
                            }
                        }
                    } else {
                        // userId 是 "无" 或 "null"，不请求
                        counter[0]--;
                        if (counter[0] == 0) {
                            seatList = seats;
                            Log.i("数据5", "" + new Gson().toJson(seatList));

                            seatAdapter.setSeatList(seatList);
                        }
                    }

                }
            }

            @Override
            public void onFailure(Call<PageSeatListResponse> call, Throwable t) {
                Log.e("SeatTest", "网络请求失败：" + t.getMessage());
                Toast.makeText(AdminSeatControlActivity.this, "网络失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadAllQyAdmins() {
        apiService.getAllQyAdmins(token).enqueue(new Callback<ApiResponse<List<UserInfo>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<UserInfo>>> call, Response<ApiResponse<List<UserInfo>>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getCode() == 200) {
                    List<UserInfo> adminList = response.body().getData();
                    List<String> adminNames = new ArrayList<>();
                    qyAdminMap.clear();

                    for (UserInfo admin : adminList) {
                        String name = admin.getUserName();
                        String id = String.valueOf(admin.getId());
                        adminNames.add(name);
                        qyAdminMap.put(name, id);
                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<>(AdminSeatControlActivity.this,
                            android.R.layout.simple_spinner_item, adminNames);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinnerAdmin.setAdapter(adapter);
                } else {
                    Toast.makeText(AdminSeatControlActivity.this, "获取管理员列表失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<UserInfo>>> call, Throwable t) {
                Toast.makeText(AdminSeatControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadBindableUsers(String seatPlace) {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String identity = sp.getString("identity", "");
        String userQy = sp.getString("qy", "");

//        // 根据身份决定 seatPlace 参数
//        String seatPlaceToUse = null;
//        if ("区域管理员".equals(identity)) {
//            seatPlaceToUse = userQy;
//        } else if (seatPlace != null && !seatPlace.trim().isEmpty()) {
//            seatPlaceToUse = seatPlace;
//        }

        // 构造请求体
        BindUserRequest request = new BindUserRequest(1, 2000, null);
        Log.d("BindUserList", "✅ 请求体 JSON: " + new Gson().toJson(request));

        apiService.getRawBindableUsers(token, request).enqueue(new Callback<Map<String, String>>() {
            @Override
            public void onResponse(Call<Map<String, String>> call, Response<Map<String, String>> response) {
                if (response.isSuccessful()) {
                    Map<String, String> dataMap = response.body();
                    bindUserMap.clear();
                    List<String> userDisplayList = new ArrayList<>();

                    // 添加“无”选项
                    userDisplayList.add("无");
                    bindUserMap.put("无", null);

                    if (dataMap != null) {
                        for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                            String id = entry.getKey();
                            String name = entry.getValue();
                            String display = name;
                            userDisplayList.add(display);
                            bindUserMap.put(display, id);
                            //添加反向映射
                            userIdToDisplayMap.put(id, display);
                        }
                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<>(AdminSeatControlActivity.this,
                            android.R.layout.simple_spinner_item, userDisplayList);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinnerBindUser.setAdapter(adapter);
                    spinnerBindUser.setSelection(0); // 默认选中“无”
                } else {
                    Log.e("BindUserList", "❌ HTTP错误: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Map<String, String>> call, Throwable t) {
                Log.e("BindUserList", "❌ 请求失败: " + t.getMessage());
            }
        });
    }

    //旧的绑定人回显
    {
        //    private void loadBindableUsersForDialog(String seatPlace, Spinner targetSpinner, String currentBindUserIdMaybeNameOrId) {
//
//        BindUserRequest request = new BindUserRequest(1, 2000, null);
//        apiService.getRawBindableUsers(token, request).enqueue(new Callback<Map<String, String>>() {
//            @Override
//            public void onResponse(Call<Map<String, String>> call, Response<Map<String, String>> response) {
//                if (response.isSuccessful()) {
//                    Map<String, String> dataMap = response.body();
//                    List<String> userDisplayList = new ArrayList<>();
//                    userDisplayList.add("无"); // 添加无选项
//
//                    Map<String, String> tempBindMap = new HashMap<>();
//                    tempBindMap.put("无", null);
//
//                    for (Map.Entry<String, String> entry : dataMap.entrySet()) {
//                        String id = entry.getKey();
//                        String name = entry.getValue();
//                        String display = name;
//                        userDisplayList.add(display);
//                        tempBindMap.put(display, id);
//                        userIdToDisplayMap.put(id, display);
//                    }
//
//                    // 构建 Spinner 适配器
//                    ArrayAdapter<String> adapter = new ArrayAdapter<>(AdminSeatControlActivity.this,
//                            android.R.layout.simple_spinner_item, userDisplayList);
//                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//                    targetSpinner.setAdapter(adapter);
//
//                    // ✅ 设置默认选中项：无论传入的是 ID 还是名字，都尝试还原为 ID
//                    String realBindUserId = null;
//
//                    if (tempBindMap.containsValue(currentBindUserIdMaybeNameOrId)) {
//                        // 是 ID
//                        realBindUserId = currentBindUserIdMaybeNameOrId;
//                    } else {
//                        // 可能是名字，尝试反查
//                        for (Map.Entry<String, String> entry : userIdToDisplayMap.entrySet()) {
//                            if (entry.getValue().equals(currentBindUserIdMaybeNameOrId)) {
//                                realBindUserId = entry.getKey();
//                                break;
//                            }
//                        }
//                    }
//
//                    // 查找对应显示项
//                    String defaultDisplay = "无";
//                    if (realBindUserId != null) {
//                        for (Map.Entry<String, String> entry : tempBindMap.entrySet()) {
//                            if (realBindUserId.equals(entry.getValue())) {
//                                defaultDisplay = entry.getKey();
//                                break;
//                            }
//                        }
//                    }
//
//                    int pos = adapter.getPosition(defaultDisplay);
//                    targetSpinner.setSelection(pos >= 0 ? pos : 0);
//
//                    // 更新全局绑定用户映射
//                    bindUserMap.clear();
//                    bindUserMap.putAll(tempBindMap);
//                }
//            }
//
//            @Override
//            public void onFailure(Call<Map<String, String>> call, Throwable t) {
//                Log.e("BindUserList", "❌ Dialog内请求失败: " + t.getMessage());
//            }
//        });
//    }
    }

    private void loadBindableUsersForDialog(String seatPlace, SearchableSpinner targetSpinner, SeatDeatilBean seat) {
        Log.d("BindUserDialog", "开始请求绑定用户列表，seatPlace = " + seatPlace + ", 当前绑定 = " + seat.getSeatBind());

        BindUserRequest request = new BindUserRequest(1, 2000, null);
        apiService.getRawBindableUsers(token, request).enqueue(new Callback<Map<String, String>>() {
            @Override
            public void onResponse(Call<Map<String, String>> call, Response<Map<String, String>> response) {
                if (response.isSuccessful()) {
                    Map<String, String> dataMap = response.body();
                    List<String> userDisplayList = new ArrayList<>();
                    userDisplayList.add("无"); // 默认“无”选项

                    Map<String, String> tempBindMap = new HashMap<>();
                    tempBindMap.put("无", null);

                    if (dataMap != null) {
                        for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                            String id = entry.getKey();
                            String name = entry.getValue();
                            userDisplayList.add(name);
                            tempBindMap.put(name, id);
                            userIdToDisplayMap.put(id, name); // 更新反查表
                        }
                    }

                    // ✅ 补充当前绑定人（若不在 dataMap 中）
                    if (seat.getSeatBind() != null && !"无".equals(seat.getSeatBind())) {
                        String name = seat.getBindUserMap().getName();
                        String id = seat.getBindUserMap().getId();

//                        // 尝试反查：如果传的是 ID，查名字；如果是名字，查 ID
//                        if (userIdToDisplayMap.containsKey(seat.getSeatBind())) {
//                            name = userIdToDisplayMap.get(seat.getSeatBind());
//                            id = seat.getSeatBind();
//                        } else if (dataMap != null && dataMap.containsValue(seat.getSeatBind())) {
//                            name = seat.getSeatBind();
//                            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
//                                if (entry.getValue().equals(name)) {
//                                    id = entry.getKey();
//                                    break;
//                                }
//                            }
//                        }
                        Log.i("测试3", name + "--" + id);

                        if (!tempBindMap.containsValue(id)) {
                            Log.d("BindUserDialog", "⚠️ 当前绑定人不在列表，添加进 Spinner: name = " + name + ", id = " + id);
                            userDisplayList.add(name);
                            tempBindMap.put(name, id);
                        }
                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<>(AdminSeatControlActivity.this,
                            android.R.layout.simple_spinner_item, userDisplayList);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    targetSpinner.setAdapter(adapter);

                    // 自动选中当前绑定项
                    String selectedDisplay = "无";
                    for (Map.Entry<String, String> entry : tempBindMap.entrySet()) {
                        if (entry.getValue() != null && entry.getValue().equals(seat.getSeatBind())) {
                            selectedDisplay = entry.getKey();
                            break;
                        }
                        if (entry.getKey().equals(seat.getSeatBind())) {
                            selectedDisplay = entry.getKey();
                            break;
                        }
                    }

                    int pos = adapter.getPosition(selectedDisplay);
                    targetSpinner.setSelection(pos >= 0 ? pos : 0);

                    // 仅作用于当前弹窗的绑定用户映射
                    bindUserMap.clear();
                    bindUserMap.putAll(tempBindMap);
                }
            }

            @Override
            public void onFailure(Call<Map<String, String>> call, Throwable t) {
                Log.e("BindUserDialog", "❌ 请求失败: " + t.getMessage());
            }
        });
    }

    private void editItme(SeatDeatilBean seat) {
        Log.i("测试", new Gson().toJson(seatList) + "---" + new Gson().toJson(seat));

        View dialogView = getLayoutInflater().inflate(R.layout.dialog_edit_seat, null);

        EditText editSeatNum = dialogView.findViewById(R.id.edit_seat_num);
        Spinner spinnerSeatArea = dialogView.findViewById(R.id.spinner_seat_area);
        Spinner spinnerQyAdmin = dialogView.findViewById(R.id.spinner_qy_admin);
        Spinner spinnerSeatStatus = dialogView.findViewById(R.id.spinner_seat_status);
        SearchableSpinner spinnerBindUserDialog = dialogView.findViewById(R.id.spinner_bind_user);
        Button btnSave = dialogView.findViewById(R.id.btnSave);
        Button btnCancel = dialogView.findViewById(R.id.btnCancel);
        LinearLayout layoutHide = dialogView.findViewById(R.id.layout_hide);
        layoutHide.setVisibility(View.GONE);

        // 区域适配器
        String[] areaNames = AreaNameToIdMapper.getAllAreaNames();
        ArrayAdapter<String> areaAdapter = new ArrayAdapter<>(AdminSeatControlActivity.this, android.R.layout.simple_spinner_item, areaNames);
        areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerSeatArea.setAdapter(areaAdapter);

        // 初始化字段
        editSeatNum.setText(seat.getSeatNum());

        List<String> adminNames = new ArrayList<>();
        Map<String, String> adminMap = new HashMap<>();

//                // 选中当前区域
//                String areaName = AreaNameToIdMapper.getNameById(seat.getSeatPlace());
//                if (areaName != null) {
//                    int index = java.util.Arrays.asList(areaNames).indexOf(areaName);
//                    if (index >= 0) spinnerSeatArea.setSelection(index);
//                }
        spinnerQyAdmin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (adminMap != null && adminNames != null) {
                    seat.setQyAdmin(adminMap.get(adminNames.get(0)));
                }
                spinnerQyAdmin.setSelection(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        getAdminList(seat.getSeatPlace(), adminNames, adminMap, seat, spinnerQyAdmin);

        String areaName = AreaNameToIdMapper.getNameById(seat.getSeatPlace());
        String defaultArea = areaName != null ? areaName : areaNames[0];
        int index = java.util.Arrays.asList(areaNames).indexOf(defaultArea);
        if (index >= 0) spinnerSeatArea.setSelection(index);

        // ✅ 主动加载一次绑定用户列表（避免首次未触发 onItemSelected）
        String defaultAreaId = AreaNameToIdMapper.getIdByName(defaultArea);
        Log.i("测试4", seat.getSeatBind() + "--" + defaultAreaId);
        loadBindableUsersForDialog(defaultAreaId, spinnerBindUserDialog, seat);


        //管理员修改座位状态只允许选择 "空闲" 和 "维护" 两个状态（代码分别为 "0" 和 "2"）
        // 从 SeatStatusMapper 中获取仅包含 "0" 和 "2" 状态的映射
        Map<String, String> allStatus = SeatStatusMapper.getCodeToNameMap();
        List<String> statusNamesList = new ArrayList<>();
        List<String> statusCodesList = new ArrayList<>();

        for (String code : new String[]{"0", "2"}) {
            if (allStatus.containsKey(code)) {
                statusCodesList.add(code);
                statusNamesList.add(allStatus.get(code));
            }
        }

        //动态更新可绑定用户
        spinnerSeatArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedAreaName = parent.getItemAtPosition(position).toString();
                String seatPlaceId = AreaNameToIdMapper.getIdByName(selectedAreaName);

                Log.d("BindUserDialog", "调用 loadBindableUsersForDialog，seatPlaceId = " + seatPlaceId + ", currentBind = " + seat.getSeatBind());
                // 加载对应区域的绑定用户列表并自动回显当前绑定用户
                loadBindableUsersForDialog(seatPlaceId, spinnerBindUserDialog, seat);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 默认显示“无”
                loadBindableUsersForDialog(null, spinnerBindUserDialog, seat);
            }
        });

        String[] seatStatusCodes = statusCodesList.toArray(new String[0]);
        String[] seatStatusNames = statusNamesList.toArray(new String[0]);

        ArrayAdapter<String> statusAdapter = new ArrayAdapter<>(AdminSeatControlActivity.this,
                android.R.layout.simple_spinner_item, seatStatusNames);
        statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerSeatStatus.setAdapter(statusAdapter);

        // 设置默认选中项
        String currentStatus = seat.getSeatStatus(); // 例如 "0"
        for (int i = 0; i < seatStatusCodes.length; i++) {
            if (seatStatusCodes[i].equals(currentStatus)) {
                spinnerSeatStatus.setSelection(i);
                break;
            }
        }

        AlertDialog dialog = new AlertDialog.Builder(AdminSeatControlActivity.this)
                .setView(dialogView)
                .setCancelable(false)
                .create();

        RecyclerView recyclerBookingList = dialogView.findViewById(R.id.recycler_booking_list);
        BookingRecordAdapter adapter = new BookingRecordAdapter(
                seat.getSsrSeatBookingList(),
                recordId -> {
                    Log.d("BookingDelete", "recordId = " + recordId);
                    DeleteSeatBookingRequest request = new DeleteSeatBookingRequest(recordId);
                    apiService.deleteSeatBooking(token, request).enqueue(new Callback<ApiResponse<Object>>() {
                        @Override
                        public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                            if (response.isSuccessful() && response.body() != null) {
                                ApiResponse<Object> resp = response.body();
                                if (resp.getCode() == 200) {
                                    Toast.makeText(AdminSeatControlActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();  // 关闭弹窗后刷新
                                    loadSeatList();
                                } else {
                                    Toast.makeText(AdminSeatControlActivity.this, "删除失败：" + resp.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            } else {
                                Toast.makeText(AdminSeatControlActivity.this, "请求失败：" + response.code(), Toast.LENGTH_SHORT).show();
                            }
                        }


                        @Override
                        public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                            Toast.makeText(AdminSeatControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
        );


        recyclerBookingList.setLayoutManager(new LinearLayoutManager(AdminSeatControlActivity.this));
        recyclerBookingList.setAdapter(adapter);

        btnSave.setOnClickListener(v -> {
            String newSeatNum = editSeatNum.getText().toString().trim();
            String newSeatPlace = AreaNameToIdMapper.getIdByName(spinnerSeatArea.getSelectedItem().toString());
            String selectedAdminName = spinnerQyAdmin.getSelectedItem().toString();
            String newQyAdmin = adminMap.get(selectedAdminName);
            String selectedDisplay = (String) spinnerBindUserDialog.getSelectedItem();
            String newBind = bindUserMap.getOrDefault(selectedDisplay, null);
            String selectedStatusCode = seatStatusCodes[spinnerSeatStatus.getSelectedItemPosition()];

            if (newSeatNum.isEmpty() || newSeatPlace == null || newQyAdmin.isEmpty()) {
                Toast.makeText(AdminSeatControlActivity.this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }
            SeatUpdateRequest updateRequest = new SeatUpdateRequest(seat.getId(), newSeatPlace, newQyAdmin);
            updateRequest.setSeatNum(newSeatNum);
            updateRequest.setSeatBind(newBind);
            updateRequest.setSeatStatus(selectedStatusCode);
            Log.d("SeatUpdateRequest", "修改请求体 JSON: " + new Gson().toJson(updateRequest));

            apiService.seatUpdate(token, updateRequest).enqueue(new Callback<ApiResponse<Object>>() {
                @Override
                public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        ApiResponse<Object> resp = response.body();
                        if (resp.getCode() == 200) {
                            Toast.makeText(AdminSeatControlActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                            loadSeatList(); // ✅ 重新加载更新后的列表
                            dialog.dismiss();
                        } else {
                            Toast.makeText(AdminSeatControlActivity.this, "修改失败：" + resp.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(AdminSeatControlActivity.this, "请求失败：" + response.code(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                    Toast.makeText(AdminSeatControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        });
        btnCancel.setOnClickListener(v -> dialog.dismiss());
        dialog.show();
    }

    private void getAdminList(String seatPlace, List<String> adminNames, Map<String, String> adminMap, SeatDeatilBean seat, Spinner spinnerQyAdmin) {
        apiService.getQyAdminList(token, new QyAdminListRequest(seatPlace)).enqueue(new Callback<ApiResponse<List<UserItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<UserItem>>> call, Response<ApiResponse<List<UserItem>>> response) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int position =0;
                        Log.i("测试13", new Gson().toJson(response.body().getData()));
                        if (response.body() != null && response.body().getCode() == 200 && response.body().getData() != null) {
                            Log.i("测试11", "");
                            for (int i = 0; i < response.body().getData().size(); i++) {
                                adminNames.add(response.body().getData().get(i).getUserName());
                                adminMap.put(response.body().getData().get(i).getUserName(), response.body().getData().get(i).getId() + "");
                                if (seat.getQyAdminMap() != null && seat.getQyAdminMap().getId().equals(response.body().getData().get(i).getId() + "")) {
                                    Log.i("测试13", ""+i);
                                    position = i;
                                }
                            }
                        } else {
                            Log.i("测试12", "");
                            // 设置 spinner_qy_admin 的选项（此处只支持当前这个座位的管理员）
                            if (seat.getQyAdminMap() != null && !adminNames.contains(seat.getQyAdminMap().getName())) {
                                adminNames.add(0, seat.getQyAdminMap().getName());
                                adminMap.put(seat.getQyAdminMap().getName(), seat.getQyAdminMap().getId());
                                // 默认选中第一个（如果有）
//                                spinnerQyAdmin.setSelection(0);

                                Log.i("测试14", "");
                            }
                        }
                        ArrayAdapter<String> adminAdapter = new ArrayAdapter<>(AdminSeatControlActivity.this,
                                android.R.layout.simple_spinner_item, adminNames);
                        adminAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinnerQyAdmin.setAdapter(adminAdapter);
                        spinnerQyAdmin.setSelection(position);

                    }
                });
            }

            @Override
            public void onFailure(Call<ApiResponse<List<UserItem>>> call, Throwable t) {
                Toast.makeText(AdminSeatControlActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private final Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            loadSeatList();
            refreshHandler.postDelayed(this, REFRESH_INTERVAL_MS);
        }
    };


}
